<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- The above 4 meta tags *must* come first in the head; any other head content must come *after* these tags -->

    <!-- Title  -->
    <title th:text="${site_name}">Essence - Fashion Ecommerce Template</title>

    <!-- Favicon  -->
    <link rel="icon" th:href="@{/essence/img/core-img/favicon.ico}">

    <!-- Core Style CSS -->
    <link rel="stylesheet" data-th-href="@{/essence/css/core-style.css}">
    <link rel="stylesheet" data-th-href="@{/essence/style.css}">
    <link rel="stylesheet" data-th-href="@{/essence/js/xpage/xpage.css}">    

</head>

<body>
    <!-- ##### Header Area Start ##### -->
    <header class="header_area">
        <div class="classy-nav-container breakpoint-off d-flex align-items-center justify-content-between">
            <!-- Classy Menu -->
            <nav class="classy-navbar" id="essenceNav">
                <!-- Logo -->
                <a class="nav-brand" href="index.html"><img src="/essence/img/core-img/logo.png" alt=""></a>
                <!-- Navbar Toggler -->
                <div class="classy-navbar-toggler">
                    <span class="navbarToggler"><span></span><span></span><span></span></span>
                </div>
                <!-- Menu -->
                <div class="classy-menu">
                    <!-- close btn -->
                    <div class="classycloseIcon">
                        <div class="cross-wrap"><span class="top"></span><span class="bottom"></span></div>
                    </div>
                <!-- Menu -->
                <div class="classy-menu">
                    <!-- close btn -->
                    <div class="classycloseIcon">
                        <div class="cross-wrap"><span class="top"></span><span class="bottom"></span></div>
                    </div>
                    <!-- Nav Start -->
                    <div class="classynav">
                        <ul> 
                            <li th:each="nav : ${navs.children}"><a th:text="${nav.text}" th:href="${nav.url}">Pages</a>
                               <th:block th:if="${not #lists.isEmpty(nav.children)}">
                                <ul class="dropdown">
                                    <li th:each="nav1 : ${nav.children}"><a th:text="${nav1.text}" th:href="${nav1.url}">Home</a></li>
                                </ul>
                                </th:block>
                            </li>
                        </ul>
                    </div>
                    <!-- Nav End -->
                </div>
            </nav>

            <!-- Header Meta Data -->
            <th:block data-th-include="themes/essence/hmeta"></th:block>
            <!-- Header Meta Data end -->

        </div>
    </header>
    <!-- ##### Header Area End ##### -->

    <!-- ##### Right Side Cart Area ##### -->
    <th:block data-th-include="themes/essence/cart"></th:block>
    <!-- ##### Right Side Cart End ##### -->

    <!-- ##### Single Product Details Area Start ##### -->
    <section class="single_product_details_area d-flex align-items-center">

        <!-- Single Product Thumb -->
        <div class="single_product_thumb clearfix">
            <div class="product_thumbnail_slides owl-carousel">
                <img th:each="img:${product.productImages}" th:src="${img.src}"/>
                <img th:if="${#lists.isEmpty(product.productImages)}" th:src="${product.thumbnail}" alt="">
                <!-- 这个轮播图最少要求有一张图片，所以要准备好一张默认图片 -->
                <img src="/demoimgs/wangyuanjing.jpg" alt="">
            </div>
        </div>

        <!-- Single Product Description -->
        <div class="single_product_desc clearfix">
            <a href="cart.html">
                <h2 th:text=${product.title}>One Shoulder Glitter Midi Dress</h2>
            </a>
            <p class="product-price"><span class="old-price" id="originPrice" th:text="${product.originPrice}">0.00</span> <em id="price" th:text="${product.price}">0.00</em></p>
            <p class="product-desc" th:text="${product.usp}">摘要</p>

            <!-- Form -->
            <form class="cart-form clearfix" method="post">
                <!-- Select Box -->
                <div class="select-box  mt-50 mb-30" id="specArea">
                    <div class="mb-15 row spec-row" th:each="attrObj:${specSelectList}">
                     <div class="col-12">
                      <div class="btn-group btn-group-xs btn-group-justified">
					  <label th:text="${attrObj.specName+':'}" class="attr-label">属性1</label>
					  <input type="button" class="sku btn btn-primary" th:attr="attr_id=${valueObj.id}" th:value="${valueObj.specValue}" th:each="valueObj:${attrObj.values}"/>
					  </div>
                     </div>
                    </div>
                </div>
                <!-- Cart & Favourite Box -->
                <div class="cart-fav-box d-flex align-items-center">
                    <!-- Cart -->
                    <button type="button" name="addtocart" value="5" class="btn essence-btn" id="addCartBtn">加入购物车</button>
                    <!-- Favourite -->
                    <div class="product-favourite ml-4">
                        <a href="#" class="favme fa fa-heart" id="fa-heart" th:attr="favoriteId=${product.id}"></a>
                    </div>
                </div>
            </form>
        </div>
    </section>
    <!-- ##### Single Product Details Area End ##### -->
    <!-- product content begin -->
    <section class="container">
      <div class="row">
        <div class="col-lg-12"><h4 class="productContent">商品详情</h4></div>
        <div class="col-lg-12" th:utext="${product.content}">
          商品内容描述
        </div>
        <div class="col-lg-12">
          <div class="commentBar">
            <h4>评论内容</h4>
          </div>
        </div>
          <div class="col-lg-12 comments" id="commentsList">
<!--             <div class="row comment-row">
             <div class="col-lg-2 comment-author">管理员</div>
             <div class="col-lg-10">
             fvdasfdsafdsafdsaaaaaaaaaaaaadsafdsa霜期国；埃里克森 工；fjkl；dsajf奇葩
             </div>
            </div> -->
          </div>    
          <!-- pagination --> 
          <div class="col-lg-12" id="page">
          
          </div>
          <!-- pagination end -->   
        <div class="col-lg-12">
			<form role="form">
			  <div class="form-group">
			    <textarea class="form-control" rows="4" placeholder="评论内容" id="commentContent"></textarea>
			  </div>
			  <div class="form-group">
                  <th:block sec:authorize="isAuthenticated()">
                    <a href="#!" class="btn essence-btn" id="commentSureBtn">提交</a>
                  </th:block>  
                  <th:block sec:authorize="isAnonymous()">
                     <a href="/member/login" class="btn essence-btn">提交(游客)</a>
                  </th:block>			  
			  </div>
			</form>
        </div>
      </div>
    </section>
    <!-- product content end -->
    <!-- ##### Footer Area Start ##### -->
    <th:block data-th-include="themes/essence/footer"></th:block>
    <!-- ##### Footer Area End ##### -->
  <script id="commentListTemplate" type="text/x-jquery-tmpl">
            <div class="row comment-row">
             <div class="col-lg-2 comment-author">${author}</div>
             <div class="col-lg-10">
               ${content}
             </div>
            </div>
  </script>
    <!-- jQuery (Necessary for All JavaScript Plugins) -->
    <script data-th-src="@{/essence/js/jquery/jquery-2.2.4.min.js}"></script>
    <script data-th-src="@{/essence/js/jquery.tmpl.min.js}"></script>
    <!-- Popper js -->
    <script data-th-src="@{/essence/js/popper.min.js}"></script>
    <!-- Bootstrap js -->
    <script data-th-src="@{/essence/js/bootstrap.min.js}"></script>
    <!-- Plugins js -->
    <script data-th-src="@{/essence/js/plugins.js}"></script>
    <!-- Classy Nav js -->
    <script data-th-src="@{/essence/js/classy-nav.min.js}"></script>
    <!-- Active js -->
    <script data-th-src="@{/essence/js/active.js}"></script>
    <script data-th-src="@{/essence/js/product.js}"></script>
    <script data-th-src="@{/essence/js/sku.js}"></script>    
    <script data-th-src="@{/essence/js/xpage/xlPaging.js}"></script>          
<script data-th-inline="javascript">
  function formatSpec(item){
	  var itemArr = item.split(",");
	  var result = '';
	  for(var i=0;i<itemArr.length;i++){
		  result +='<span class="spec">'+itemArr[i]+'</span>';
	  }
	  return result;
  }
  var ctx = [[@{/}]];
  var productId =[[${product.id}]];
  var productName =[[${product.title}]];
  var thumbnail =[[${product.thumbnail}]];
  var specSelectListJson = [[${specSelectListJson}]];
  var specArray = $.parseJSON(specSelectListJson);
  // sku标识keys
  var keys=[];
  for(var i=0;i<specArray.length;i++){
	  keys[i]=new Array();
	  for(var j=0;j<specArray[i].values.length;j++){
		  keys[i][j]=specArray[i].values[j].id;
	  }
  }
  var skuListJson =[[${skuListJson}]];
  var skuArray = $.parseJSON(skuListJson);
  var data={};
  for(var k=0;k<skuArray.length;k++){
	  var skuObj = skuArray[k];
	  data[skuObj.specificationIds]=skuObj;
  }
//保存最后的组合结果信息
  var SKUResult = {};
  //获得对象的key
  function getObjKeys(obj) {
      if (obj !== Object(obj)) throw new TypeError('Invalid object');
      var keys = [];
      for (var key in obj)
          if (Object.prototype.hasOwnProperty.call(obj, key))
              keys[keys.length] = key;
      return keys;
  }

  //把组合的key放入结果集SKUResult
  function add2SKUResult(combArrItem, sku) {
  	var key = combArrItem.join(",");
      if(SKUResult[key]) {//SKU信息key属性·
          SKUResult[key].stock += sku.stock;
          SKUResult[key].prices.push(sku.price);
          SKUResult[key].originPrices.push(sku.originPrice);
      } else {
          SKUResult[key] = {
        	  // 规格没有图片，早直接引用商品主图
        	  img: sku.imgUrl==""?thumbnail:sku.imgUrl,
              stock : sku.stock,
              prices : [sku.price],
              originPrices: [sku.originPrice]
          };
      }
  }

  //初始化得到结果集
  function initSKU() {
      var i, j, skuKeys = getObjKeys(data);
      for(i = 0; i < skuKeys.length; i++) {
          var skuKey = skuKeys[i];//一条SKU信息key
          var sku = data[skuKey];	//一条SKU信息value
          var skuKeyAttrs = skuKey.split(","); //SKU信息key属性值数组
  		skuKeyAttrs.sort(function(value1, value2) {
  			return parseInt(value1) - parseInt(value2);
  		});

          //对每个SKU信息key属性值进行拆分组合
  		var combArr = combInArray(skuKeyAttrs);
  		for(j = 0; j < combArr.length; j++) {
  			add2SKUResult(combArr[j], sku);
  		}

          //结果集接放入SKUResult
          SKUResult[skuKeyAttrs.join(",")] = {
        		// 规格没有图片，早直接引用商品主图
        	  img:sku.imgUrl==""?thumbnail:sku.imgUrl,
              stock:sku.stock,
              prices:[sku.price],
              originPrices:[sku.originPrice]
          }
      }
  }

  /**
   * 从数组中生成指定长度的组合
   * 方法: 先生成[0,1...]形式的数组, 然后根据0,1从原数组取元素，得到组合数组
   */
  function combInArray(aData) {
  	if(!aData || !aData.length) {
  		return [];
  	}

  	var len = aData.length;
  	var aResult = [];

  	for(var n = 1; n < len; n++) {
  		var aaFlags = getCombFlags(len, n);
  		while(aaFlags.length) {
  			var aFlag = aaFlags.shift();
  			var aComb = [];
  			for(var i = 0; i < len; i++) {
  				aFlag[i] && aComb.push(aData[i]);
  			}
  			aResult.push(aComb);
  		}
  	}
  	
  	return aResult;
  }


  /**
   * 得到从 m 元素中取 n 元素的所有组合
   * 结果为[0,1...]形式的数组, 1表示选中，0表示不选
   */
  function getCombFlags(m, n) {
  	if(!n || n < 1) {
  		return [];
  	}

  	var aResult = [];
  	var aFlag = [];
  	var bNext = true;
  	var i, j, iCnt1;

  	for (i = 0; i < m; i++) {
  		aFlag[i] = i < n ? 1 : 0;
  	}

  	aResult.push(aFlag.concat());

  	while (bNext) {
  		iCnt1 = 0;
  		for (i = 0; i < m - 1; i++) {
  			if (aFlag[i] == 1 && aFlag[i+1] == 0) {
  				for(j = 0; j < i; j++) {
  					aFlag[j] = j < iCnt1 ? 1 : 0;
  				}
  				aFlag[i] = 0;
  				aFlag[i+1] = 1;
  				var aTmp = aFlag.concat();
  				aResult.push(aTmp);
  				if(aTmp.slice(-n).join("").indexOf('0') == -1) {
  					bNext = false;
  				}
  				break;
  			}
  			aFlag[i] == 1 && iCnt1++;
  		}
  	}
  	return aResult;
  } 



  //初始化用户选择事件
  $(function() {
  	initSKU();
  	$('.sku').each(function() {
  		var self = $(this);
  		var attr_id = self.attr('attr_id');
  		if(!SKUResult[attr_id]) {
  			self.attr('disabled', 'disabled');
  		}
  	}).click(function() {
  		var self = $(this);
  		//选中自己，兄弟节点取消选中
  		self.toggleClass('bh-sku-selected').siblings().removeClass('bh-sku-selected');
  		//已经选择的节点
  		var selectedObjs = $('.bh-sku-selected');
  		if(selectedObjs.length) {
  			//获得组合key价格
  			var selectedIds = [];
  			selectedObjs.each(function() {
  				selectedIds.push($(this).attr('attr_id'));
  			});
  			selectedIds.sort(function(value1, value2) {
  				return parseInt(value1) - parseInt(value2);
  			});
  			var len = selectedIds.length;
  			var prices = SKUResult[selectedIds.join(',')].prices;
  			var maxPrice = Math.max.apply(Math, prices);
  			var minPrice = Math.min.apply(Math, prices);
  			var originPrices = SKUResult[selectedIds.join(',')].originPrices;
  			var maxOriginPrice = Math.max.apply(Math, originPrices);
  			var minOriginPrice = Math.min.apply(Math, originPrices);
  			$('#price').text(maxPrice > minPrice ? minPrice + "-" + maxPrice : maxPrice);
  			$('#originPrice').text(maxOriginPrice > minOriginPrice ? minOriginPrice + "-" + maxOriginPrice : maxOriginPrice);
  			//用已选中的节点验证待测试节点 underTestObjs
  			$(".sku").not(selectedObjs).not(self).each(function() {
  				var siblingsSelectedObj = $(this).siblings('.bh-sku-selected');
  				var testAttrIds = [];//从选中节点中去掉选中的兄弟节点
  				if(siblingsSelectedObj.length) {
  					var siblingsSelectedObjId = siblingsSelectedObj.attr('attr_id');
  					for(var i = 0; i < len; i++) {
  						(selectedIds[i] != siblingsSelectedObjId) && testAttrIds.push(selectedIds[i]);
  					}
  				} else {
  					testAttrIds = selectedIds.concat();
  				}
  				testAttrIds = testAttrIds.concat($(this).attr('attr_id'));
  				testAttrIds.sort(function(value1, value2) {
  					return parseInt(value1) - parseInt(value2);
  				});
  				if(!SKUResult[testAttrIds.join(',')]) {
  					$(this).attr('disabled', 'disabled').removeClass('bh-sku-selected');
  				} else {
  					$(this).removeAttr('disabled');
  				}
  			});
  		} else {
  			//设置默认价格
  			$('#price').text('--');
  			//设置属性状态
  			$('.sku').each(function() {
  				SKUResult[$(this).attr('attr_id')] ? $(this).removeAttr('disabled') : $(this).attr('disabled', 'disabled').removeClass('bh-sku-selected');
  			})
  		}
  	});
  });
  // 初始化购物车
  $Product.refreshCart();
  // 添加购物车
  $("#addCartBtn").click(function(){
	  var selectIds=[];
	  var _flag = true;
	 $(".spec-row").each(function(){
		 var selSpecObj=$(this).find(".bh-sku-selected");
		 var attrName = $(this).find(".attr-label").text()
		 if(selSpecObj==undefined || selSpecObj.length==0){
			 alert("请选择"+attrName);
			 _flag=false;
			 return false;
		 }
		 var specId = selSpecObj.attr("attr_id");
		 selectIds.push(specId);
	 })
	 if(_flag==false){
		 return false;
	 }
	 selectIds.sort(function(value1, value2) {
  		return parseInt(value1) - parseInt(value2);
  	  });
	 var specIds = selectIds.join(",");
	 if(SKUResult[specIds]){
		var imgUrl = SKUResult[specIds].img;
		$Product.addToCart(productId,productName,specIds,imgUrl);
	 }else{
		 alert("商品规格信息错误");
	 }
  });
// 添加收藏id="fa-heart" th:attr="favoriteId=${product.id}"
$("#fa-heart").click(function(){
	var productId = $(this).attr("favoriteId");
	$Product.addFavoriteProduct(productId);
})
// 提交商品评论
$("#commentSureBtn").click(function(){
	var content = $("#commentContent").val();
	if(content==undefined||content.trim()==""){
		alert("评论内容不能为空");
		return false;
	}
	$.post(ctx+"member/productComment/save",{productId:productId,content:content},function(res){
		refreshComment();
		$("#commentContent").val("");
	})
})


// 分页相关
var pageSize = 5;
// 按页查询
function refreshComment(pageNum){
	$.getJSON("/productComment/list",{productId:productId,pageSize:pageSize,pageNum:pageNum},function(data){
		total = data.total;
		if(data.rows && data.rows.length>0){
			 $('#commentsList').html($('#commentListTemplate').tmpl(data.rows))
		}else{
			 $('#commentsList').html('暂无评论')
		}
	})	
}
// 加载商品评论
function initComment(pageNum){
	// 加载首页内容并初始化ajax分页对象
	$.getJSON("/productComment/list",{productId:productId,pageSize:pageSize,pageNum:1},function(data){
		total = data.total;
		if(data.rows && data.rows.length>0){
			// 加载首页内容并初始化ajax分页对象
			 $('#commentsList').html($('#commentListTemplate').tmpl(data.rows))
			 // 计算总页数
			  var totalPage = Math.ceil(data.total/pageSize);
			// console.log(totalPage);
			 // 分页初始化
			    let a =new Paging('page', {
			        nowPage: pageNum, // 当前页码
			        pageNum: totalPage, // 总页码
			        buttonNum: 5, //要展示的页码数量
			        canJump: 1,// 是否能跳转。0=不显示（默认），1=显示
			        showOne: 1,//只有一页时，是否显示。0=不显示,1=显示（默认）
			        callback: function (num) { //回调函数
			        	refreshComment(num);
			        }
			    })
			 // 初始化分页
		}else{
			 $('#commentsList').html('暂无评论')
		}
	})
}
initComment();
</script>
</body>

</html>